﻿package com.sz.login.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sz.login.bmo.ILoginBMO;
import com.sz.manager.dao.IManagerDAO;

public class LoginServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected final Log logger = LogFactory.getLog(getClass());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
//		PrintWriter out = response.getWriter();
//		out.println("错误的调用");
		//response.sendRedirect("index.jsp?username=aaa&message=kao");
		
		
		
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String url = null;
			
			//ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
			ServletContext servletContext = request.getSession().getServletContext();        
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
			
			ILoginBMO login = (ILoginBMO) context.getBean("LoginBMO");
			Map r = login.doLogin(request.getParameter("username"), request.getParameter("password"),
					request.getParameter("region"), request.getRemoteAddr());
			if(r.get("MESSAGE") != null) {
				url = "/index.jsp?message="+r.get("MESSAGE");
				request.getRequestDispatcher(url).forward(request, response);
			} else { //登陆成功
				
				//取用户的模块权限信息
				IManagerDAO dao = (IManagerDAO)context.getBean("ManagerDAO");
				List list = (List)dao.queryManagerModules(r.get("MANAGER_ID").toString());
				
				//写session  不可写成request.setAttribute，response.sendRedirect后会取不到
				//此处setAttribute,记得LogoutServlet也要相应改动
				request.getSession().setAttribute("userid", r.get("MANAGER_ID").toString());
				request.getSession().setAttribute("username", request.getParameter("username"));
				request.getSession().setAttribute("regionid", request.getParameter("region"));
				request.getSession().setAttribute("regionname", r.get("REGION_NAME"));
				request.getSession().setAttribute("usertype",  r.get("TYPE")!=null ? r.get("TYPE").toString():"0");
				request.getSession().setAttribute("modules", list);
				
				//跳转页面
				url = "mainmenu.do";
				response.sendRedirect(url);
			}			

		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e.getMessage());
		}

	}


}
